var currPage = 1;
var dataDetail=null;
var status = null;
var id = null;
var inColorList = null;
var outColorList = null;
var next_deadline_limt = null;
var up_deadline_limt = null;
var source = null;
;layui.define(function(e) {
    layui.use(['table','layer','form','laydate'], function(){
         var $ = layui.$
            ,layer = layui.layer
            ,form = layui.form
            ,table = layui.table
            ,laydate = layui.laydate;
         $(function(){
        	 loadfinanicalInfo(id);
        	 clearFinancial();
         })
         // 门店
         $("input[name='shopId']").val(globalStoreId);
         // 获取授信额度
         $(function(){
             $.ajax({
         		url: hostUrl+'/purchaseIntentioOrderHead/getIntentioOrderInfo',
                 type: "post",
                 data: null,
                 dataType: "json",
                 async: false,
                 contentType: "application/json; charset=utf-8",
                 success: function(data) {
                	 if(data.status == 1){
                		 $("input[name='creditLimit']").val(data.creditlimit);
                	 }else{
                		 Layer.showFailMsg("获取经销商授信额度失败,请稍后再试...");
                	 }
                 },
         	 	error: function(data) { 
         	 		 Layer.showFailMsg("获取经销商授信额度失败,请稍后再试...");
         	 	}
             });
         })
         
         //重新渲染表单
         function renderForm(){
           layui.use('form', function(){
            	var form = layui.form;
            	form.render();
           });
         }
         
         
         //初始化，选择品牌下拉列表
         function loadfinanicalInfo(id){
         	$.ajax({
         		url: hostUrl+'/dealerFinanicalInfo/getDealerFinanicalBranch',
                 type: "post",
                 data: {"id":id},
                 dataType: "json",
                 async : false,
                 success: function(data) {
                	 if(data.status == 1){
                 	    var mydata = data.finanicalList;
	                 	if(id){
	                 		for ( var i = 0; i <mydata.length; i++){
	                 			var server_interest =  mydata[i].server_interest; //服务日费率
	                 			var day_interest_rate =  mydata[i].day_interest_rate; //日利率
	                 			$("input[name=servInterestRate]").val(server_interest);
	                 			$("input[name=interestRate]").val(day_interest_rate);
	                 			up_deadline_limt =  mydata[i].up_deadline_limt; //期限上
	                 			next_deadline_limt =  mydata[i].next_deadline_limt; //期限上
	                 			
	                 		}
	                 	}else{
	                 		for ( var i = 0; i <mydata.length; i++){
	                 			var value = mydata[i].id;
	                 			var name =  mydata[i].finanical_name;
	                 			var server_interest =  mydata[i].server_interest; //服务日费率
	                 			var day_interest_rate =  mydata[i].day_interest_rate; //日利率
	                 			$("#financialBranch option:eq(0)").after("<option value='"+value+"'>"+name+"</option>");
	                 		}
	                 	}
                	 }else{
                		 Layer.showFailMsg("获取融资产品失败,请稍后再试...");
                	 }
                 	renderForm();
                 },
         		error: function(data) { 
         			 Layer.showFailMsg("获取融资产品失败,请稍后再试...");
         	 	}
             }); 
         }
         
         //融资产品
        form.on('select(financialBranch)', function(data){
        	 $("#financialProportion option:not(:first)").remove();
        	 var id = $("#financialBranch option:selected").val();
        	 clearFinancial();
        	 if(id){
        		 loadfinanicalInfo(id);
        		 loadfinancialProportion(id);
        	 }
        	 if($("select[name=financialProportion]").val() && $("select[name=financialBranch]").val()){
         		calculateDownpayment();
         	}
        	 
  		});
         
         // 融资比例
         form.on('select(financialProportion)', function(data){
        	if($("select[name=financialProportion]").val() && $("select[name=financialBranch]").val()){
        		calculateDownpayment();
        	}
        	 
  		});
         
     function loadfinancialProportion(id){
    		if(id=="" || id==" " || id==null){
    			Layer.showAlert("请先选择融资产品！");
    			return;
    		}
    		$.ajax({
    			url:  hostUrl+'/dealerFinanicalInfo/getDealerFinanicalProportion',
    	        type: "post",
    	        data: {"id":id},
    	        dataType: "json",
    	        success: function(data) {
    	        	 if(data.status == 1){
	    	        	var mydata = data.resultProportion;
	    	        	for ( var i = 0; i <mydata.length; i++){
	    					var value= mydata[i];
	    					var name= mydata[i]+'%';
	    					$("#financialProportion option:eq(0)").after("<option value='"+value+"'>"+name+"</option>");
	    				}
    	        	 }else{
    	        		 Layer.showFailMsg("获取融资比例失败,请稍后再试...");
    	        	 }
    	        	renderForm();
    	        },
         		error: function(data) { 
         			 Layer.showFailMsg("获取融资比例失败,请稍后再试...");
        	 	}
    	    }); 
    	}
      var getId = (function () {
         var i = 0;
         return function () {
             return i++;
         };
      })(); 
       //-录入车型
       $("#inputCar").click(function () {
           var index = layer.open({
               type: 2
               ,id: (new Date()).valueOf()
               ,title: '编辑'
               ,content: hostUrl+'/dealercarsource/inputCar.do' //跳转路径
               ,area: ['500px', '500px']
               ,btn:['确认','取消']
               ,maxmin: true
               ,success: function(layero, index){
                   var body = layer.getChildFrame('body', index);
                   var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
               },
               yes: function (index,layero) {
            	   var j = getId();
            	   // 清空金融方案信息
            	   $("input[name=paymentType]").removeAttr("disabled");
            	   $(".financing").removeClass("layui-hide");
                   $(".fullPayment").addClass("layui-hide");
                   $(".financing").addClass("layui-hide");
                   clear();
            	   //==验证校验后台方法必填项
            	   var body = layer.getChildFrame('body', index);
            	   var checkflag=true;
            	    // 校验必填项
            	   $(body.find("input"),body.find("select")).each(function(){
            			if($(this).val() == null || $(this).val() ==""){
            				if($(this).parent().prev().text()==""|| $(this).parent().prev().text()==null){
            					Layer.showAlert("【外观/内饰颜色】为必填字段*");
            					checkflag=false;
                				return false;
            				}
            				Layer.showAlert("【"+$(this).parent().prev().text()+"】为必填字段");
            				checkflag=false;
            				return false;
            			}
            		});
            		
            	  var carTableLength = parseInt(body.find("input[name=order_qty]").val());
            	  var start_amount = parseInt(body.find("input[name=start_amount]").val());
            	  if(carTableLength < start_amount){
            		  Layer.showFailMsg("该车型起订数量为:【"+start_amount+"】,请修改数量！");
            		  return false;
            	  }
            	  if(!checkflag){return false;}
            		
                   var carSourceId = body.find("input[name=id]").val();//id
                   //校验当前经销商是否在该销售区域
                   $.ajax({
           			url:  hostUrl+'/purchaseIntentioOrderHead/isDealerExistModel',
           	        type: "post",
           	        data: {"carSourceId":carSourceId},
           	        dataType: "json",
           	        async:false,
           	        success: function(data) {
           	        	status = data.status;
           	        	if(status != 0){
           	        		var msg = data.msg;
           	        		Layer.showFailMsg(msg);
           	        		return false;
           	        	}
           	         }
           	       }); 
                   if(status == 0) {
	                   var carTableHtml='<div class="car_table table'+ index+'">\n' +
	                   '                        <div class="layui-btn-container">\n' +
	                   '                            <a href="javascript:;" class="layui-btn layui-btn-sm layui-bg-blue carEdit" id="edit'+index+'">编辑</a>\n' +
	                   '                            <a href="javascript:;" class="layui-btn layui-btn-sm layui-bg-red carDelete" id="delete'+index+'">删除</a>\n' +
	                   '                        </div>\n' +
	                   '                        <input type="hidden" id="table'+ index +'" name="table" value=""/>' +
	                   '                        <table class="layui-table">\n' +
	                   '                            <thead>\n' +
	                   '                             <tr>\n' +
	                   '                                <th width="25%">品牌</th>\n' +
	                   '                                <th width="25%">车系</th>\n' +
	                   '                                <th width="25%">车型</th>\n' +
	                   '                                <th width="25%">外观/内饰颜色</th>\n' +
	                   '                                <th width="25%">车源</th>\n' +
	                   '                            </tr>\n' +
	                   '                            </thead>\n' +
	                   '                            <tbody>\n' +
	                   '                            </tbody>\n' +
	                   '                        </table>\n' +
	                   '                    </div>'
	                   //----
	                   var orderQty = body.find('input[name=order_qty]').val();
	                   var brandName = body.find('input[name=brand_name]').val();
	                   var seriesName = body.find('input[name=series_name]').val();
	                   var vehicleTypeName = body.find('input[name=car_type_name]').val();
	                   var carColor = body.find('select[name=out_color]').val()+"/"+body.find("select[name=in_color]").val();
	                   var inColor = body.find("select[name=in_color]").val();
	                   var outColor = body.find('select[name=out_color]').val();
	                   var carSource = body.find('select[name=car_source]').val();
	                   var startAmount = body.find('input[name=start_amount]').val();
	                   $("#car_table").append(carTableHtml);
	                   var tbody = $("#car_table .layui-table tbody");
	                   var tbodyLength = $("#car_table .layui-table tbody").length;
	                   tbody.eq(tbodyLength-1).empty();
	                   for(var i=0;i<carTableLength;i++){
	                	   j=getId();
	                       tbody.eq(tbodyLength-1).prepend('<tr>\n' +
	                    	'	   <input type="hidden" class="carSourceId" name="orderCarList['+ j +'].carSourceId" value="'+carSourceId+'" readonly/>\n' +
	                    	'	   <input type="hidden" class="orderQty" name="orderCarList['+ j +'].orderQty" value="'+orderQty+'" readonly/>\n' +
	                    	'	   <input type="hidden" class="startAmount" name="orderCarList['+ j +'].startAmount" value="'+startAmount+'" readonly/>\n' +
	                       '                                <td><input type="text" class="brand" name="orderCarList['+ j +'].brandName" value="'+brandName+'" readonly/></td>\n' +
	                       '                                <td><input type="text" class="carSeries" name="orderCarList['+ j +'].seriesName" value="'+seriesName+'" readonly/></td>\n' +
	                       '                                <td><input type="text" class="carType" name="orderCarList['+ j +'].vehicleTypeName" value="'+vehicleTypeName+'" readonly/></td>\n' +
	                       '                                <td><input type="text" class="carColor" name="orderCarList['+ j +'].carColor" value="'+carColor+'" readonly/></td>\n' +
	                       '	    <input type="hidden" class="inColor" name="orderCarList['+ j +'].inColor" value="'+inColor+'" readonly/>\n' +
	                   	   '	   <input type="hidden" class="outColor" name="orderCarList['+ j +'].outColor" value="'+outColor+'" readonly/>\n' +
	                       '                                <td><input type="text" class="carSource" name="orderCarList['+ j +'].carSource" value="'+carSource+'" readonly/></td>\n' +
	                       '                            </tr>')
	                   }
	                   var table_value = $('.table'+ index+'').find(".carSourceId").eq(0).val()+","+$('.table'+ index+'').find(".orderQty").eq(0).val();
	                   $('#table'+ index +'').val(table_value);
	               $("#edit"+index+"").click(function () {
	            	   j=getId();
	                   carEdit($(this))
	                   editFlag = false;
	                   $("input[name=paymentType]").attr("checked",false);
	                   form.render();
	               })
	               $("#delete"+index+"").click(function () {
	                   carDelete($(this))
	                   if($("#car_table").children().length == 0){
	                       $("input[name=paymentType]").attr("disabled",true).attr("checked",false);
	                       form.render();
	                   }
	               })
	               if($("#car_table").children().length != 0){
	                   $("input[name=paymentType]").attr("disabled",false).attr("checked",false);
	                   form.render();
	               }
	                clear();
	                form.render();
	                layer.close(index)
                 }
               },
           });
           layer.full(index);
       })
        var radio =  form.on('radio(payment)', function (data) {
            if(data.elem.title == "融资"){
                $(".financing").removeClass("layui-hide")
                $(".fullPayment").addClass("layui-hide")
            }
            if(data.elem.title == "全款"){
                $(".financing").addClass("layui-hide")
                $(".fullPayment").removeClass("layui-hide")
                var table = $("#car_table table");
                table.each(function (e) {
                    var tableName = $(this).attr("name");
                    $(this).attr("name",tableName+"["+e+"]")
                })
                var tr = $("#car_table tbody tr");
                tr.each(function (e) {
                    tr.eq(e).find("td").each(function (q) {
                        var tdName = $(this).attr("name");
                        $(this).attr("name",tdName+"["+q+"]")
                    })
                })
                
                var formArray = $("#formOrder").serializeArray();
                var obj = {};
                $.each(formArray, function () {
            		if (obj[this.name] !== undefined) {
            			if (!obj[this.name].push) {
            				obj[this.name] = [obj[this.name]];
            			}
            			obj[this.name].push(this.value || '');
            		} else {
            			obj[this.name] = this.value || '';
            		}
                });
                var comMap = {"data":JSON.stringify(obj)};
                // 计算意向订单总价格
                $.ajax({
            		url: hostUrl+'/purchaseIntentioOrderHead/calculateOrderAmt',
                    type: "post",
                    data: comMap,
                    dataType: "json",
                    async: false,
                    success: function(data) {
                    	if(data.status == 1){
                    		var data = data.data;
                    		$('input[name=totalMoney]').val(data.result);
                    	}else{
                    		Layer.showAlert("计算订单金额失败！");
                    	}
                    },
            	 	error: function(data) { 
             		 	Layer.showAlert("计算订单金额失败！");
            	 	}
                });
                
            }
        });
      // 计算首付
       function calculateDownpayment() {
    	   if($("select[name=financialBranch]").val() == null || $("select[name=financialBranch]").val() == ""){
    		   Layer.showAlert("融资产品不能为空！");
    		   return false;
    	   }
    	   if($("select[name=financialProportion]").val() == null || $("select[name=financialProportion]").val() == ""){
    		   Layer.showAlert("融资比例不能为空！");
    		   return false;
    	   }
    	   var table = $("#car_table table");
           table.each(function (e) {
               var tableName = $(this).attr("name");
               $(this).attr("name",tableName+"["+e+"]")
           })
           var tr = $("#car_table tbody tr");
           tr.each(function (e) {
               tr.eq(e).find("td").each(function (q) {
                   var tdName = $(this).attr("name");
                   $(this).attr("name",tdName+"["+q+"]")
               })
           })
           var formArray = $("#formOrder").serializeArray();
           var obj = {};
           $.each(formArray, function () {
       		if (obj[this.name] !== undefined) {
       			if (!obj[this.name].push) {
       				obj[this.name] = [obj[this.name]];
       			}
       			obj[this.name].push(this.value || '');
       		} else {
       			obj[this.name] = this.value || '';
       		}
           });
           var comMap = {"data":JSON.stringify(obj)};
           // 计算意向订单总价格
           $.ajax({
       		url: hostUrl+'/purchaseIntentioOrderHead/calculateOrderAmt',
               type: "post",
               data: comMap,
               dataType: "json",
               async: false,
               success: function(data) {
            	   if(data.status == 1){
	               		var data = data.data;
		               	$('input[name=totalMoney]').val(data.result);//融资额
		               	$('input[name=downPaymentAmt]').val(data.downPaymentAmt);//首付额
            	   }else{
            		   Layer.showAlert("计算订单金额失败！"); 
            	   }
               },
       	 	error: function(data) { 
       	 	      Layer.showAlert("计算订单金额失败！");
       	 	}
           });
	  }
        //编辑弹框
        function carEdit(obj) {
            var index = layer.open({
                type: 2
                ,id: (new Date()).valueOf()
                ,title: '编辑'
                ,content: hostUrl+'/dealercarsource/inputCar.do' //跳转路径
                ,area: ['500px', '500px']
                ,maxmin: true
                ,btn:['确定','取消']
                ,success: function(layero,index){
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                    var idx = obj.parent().parent().find(".carSourceId").eq(0).val();
                      id = null;
                      loadCarSource(id,body);
                      id = idx;
                      loadCarSource(id,body);
                     // alert(source)
                     // var carSource = obj.parent().parent().find(".carSource").eq(0).val();
                      var carSource = source;
                      var orderQty = obj.parent().parent().find(".orderQty").eq(0).val();
                      var carColor = obj.parent().parent().find(".carColor").eq(0).val();
                      var outColor = obj.parent().parent().find(".outColor").eq(0).val();
                      var inColor = obj.parent().parent().find(".inColor").eq(0).val();
                      var startAmount = obj.parent().parent().find(".startAmount").eq(0).val();//==
                      body.find("input[name=id]").val(idx);
                      body.find("input[name=order_qty]").val(orderQty);
                      body.find("select[name=car_source]").val(carSource);
                      body.find("select[name=out_color]").val(outColor);
                      body.find("select[name=in_color]").val(inColor);
                      body.find("input[name=start_amount]").val(startAmount);
                    
                }
                ,yes:function (index,layero) {
                	 var body = layer.getChildFrame('body', index);
                     // 起订数量
                     var carTableLength = parseInt(body.find("input[name=order_qty]").val());
               	     var start_amount = parseInt(body.find("input[name=start_amount]").val());
		           	 if(carTableLength < start_amount){
		           		Layer.showFailMsg("该车型起订数量为:【"+start_amount+"】,请修改数量！");
		           		return false;
		           	  }
                     
                     var carColor = body.find('select[name=out_color]').val()+"/"+body.find("select[name=in_color]").val();
                     obj.parent().parent().find("tbody").html("");
                     for(var i=0;i<carTableLength;i++){
                    	 j = getId();
                         obj.parent().parent().find("tbody").prepend('<tr>\n' +
                                 '	   <input type="hidden" class="carSourceId" name="orderCarList['+ j +'].carSourceId" value="'+body.find("input[name=id]").val()+'" readonly/>\n' +
                             	 '	   <input type="hidden" class="orderQty" name="orderCarList['+ j +'].orderQty" value="'+body.find("input[name=order_qty]").val()+'" readonly/>\n' +
                             	 '	   <input type="hidden" class="inColor" name="orderCarList['+ j +'].inColor" value="'+body.find("select[name=in_color]").val()+'" readonly/>\n' +
                              	 '	   <input type="hidden" class="outColor" name="orderCarList['+ j +'].outColor" value="'+body.find("select[name=out_color]").val()+'" readonly/>\n' +
                         '                                <td><input class="orderCarList['+ j +'].brand" name="brand" type="text" value="'+ body.find("input[name=brand_name]").val() +'"/></td>\n' +
                         '                                <td><input class="orderCarList['+ j +'].carSeries" name="carSeries" type="text" value="'+ body.find("input[name=series_name]").val() +'"/></td>\n' +
                         '                                <td><input class="orderCarList['+ j +'].carType" name="carType" type="text" value="'+ body.find("input[name=car_type_name]").val() +'"/></td>\n' +
                         '                                <td><input class="orderCarList['+ j +'].carColor" name="carColor" type="text" value="'+carColor+'"/></td>\n' +
                         '                                <td><input class="orderCarList['+ j +'].carSource" name="carSource" type="text" value="'+ body.find("input[name=car_name]").val() +'"/></td>\n' +
                         '                            </tr>')
                     }
                     $("input[name=paymentType]").removeAttr("checked");
                     clear();
                 	 renderForm();
                     layer.close(index);
                }
            });
            layer.full(index);
        }
       
       function carDelete(obj) {
           obj.parent().parent().remove();
           $("input[name=paymentType]").removeAttr("checked");
            clear();
         	renderForm();
       }
       
     //初始化，选择品牌下拉列表
       function loadCarSource(id,body){
    	   var conMap={"id":id};
       	$.ajax({
       		url: hostUrl+'/purchaseIntentioOrderHead/getCarSourcesInfo',
               type: "post",
               data: JSON.stringify(conMap),
               dataType: "json",
               async : false,
               contentType: "application/json; charset=utf-8",
               beforeSend:function(){
               },
               success: function(data) {
               	var mydata = data.carSources;
               	if(id){
               		for ( var i = 0; i <mydata.length; i++){
               			var name =  mydata[i].brand_name+"/"+mydata[i].series_name+"/"+mydata[i].car_type_name;
               			source = name;
               			var value = mydata[i].id;
               			body.find('input[name=brand_name]').val(mydata[i].brand_name);
               			body.find('input[name=id]').val(value);
               			body.find('input[name=car_name]').val(name);
               			body.find('input[name=series_name]').val(mydata[i].series_name);
               			body.find('input[name=car_type_name]').val(mydata[i].car_type_name);
               			body.find("select[name=car_source]").append("<option data-id='"+value+"' value='"+name+"'>"+name+"</option>")
               		    inColorList = null;
               		    outColorList = null;
               			inColorList = mydata[i].in_color.split("、"); // 内颜色
               			outColorList = mydata[i].out_color.split("、"); //外颜色
               			loadInColor(id,body);
               			loadOutColor(id,body);
               		}
               	}else{
               		//body.find("select[name=car_source]").html("");
               		//body.find("select[name=car_source]").remove();
               		//body.find("select[name=car_source]").append("<option data-id='id' value='names'>请选择车辆/品牌/车型</option>");
               		//body.find("#car_source option:not(:first)").remove();
               		/*for ( var i = 0; i <mydata.length; i++){
               			var name =  mydata[i].brand_name+"/"+mydata[i].series_name+"/"+mydata[i].car_type_name;
               			var value = mydata[i].id;
               			body.find("select[name=car_source]").append("<option data-id='"+value+"' value='"+name+"'>"+name+"</option>");
               		}*/
               	}
               	renderForm();
               },
       		error: function(data) { 
       	 	}
           }); 
       }
       
       // 外颜色
       function loadOutColor(id,body){
    	   if(outColorList){
    		   if(id){
    			   body.find("#out_color option:not(:first)").remove();
    			   for ( var i = 0; i <outColorList.length; i++){
    				   var outColor = outColorList[i];
    				   body.find("#out_color option:eq(0)").after("<option value='"+outColor+"'>"+outColor+"</option>");
    			   }
    		   }
    	   }
    	   renderForm();
    	   
       }
       //内颜色
       function loadInColor(id,body){
    	   if(inColorList){
    		   if(id){
    			   body.find("#in_color option:not(:first)").remove();
    			   for ( var i = 0; i <inColorList.length; i++){
    				   var inColor = inColorList[i];
    				   body.find("#in_color option:eq(0)").after("<option value='"+inColor+"'>"+inColor+"</option>");
    			   }
    		   }
    	   }
    	   renderForm();
       }
       
       // 编辑删除数据清空
       function clear(){
    		$('input[name=totalMoney]').val("");//融资额
           	$('input[name=downPaymentAmt]').val("");//首付额
           	$("select[name=financialBranch]").val("");//融资产品
           	$("select[name=financialProportion]").val("");//融资比例
           	$("input[name=allottedTime]").val("");//期限
           	clearFinancial();
       }
       // 编辑删除数据清空
       function clearFinancial(){
    		$("input[name=servInterestRate]").val("");
			$("input[name=interestRate]").val("");
			$("input[name=downPaymentAmt]").val("");
			$("select[name=financialProportion]").val("");
       }
     // 监听下订按钮
       form.on('submit(underOrderSave)', function(data){
    	 var checkflag=true;
		 var paymentType = $("input[name='paymentType']:checked").val();
	  	 if(typeof(paymentType) == 'undefined' || paymentType == ''){
	   		 Layer.showFailMsg("【支付方式】为必填字段");
	   		 return false;
	    }
	  	var creditlimit = $("input[name='creditlimit']").val();
	  	// 融资数据校验
	  	if(paymentType == 0){
	  		 if($("select[name=financialBranch]").val() == null || $("select[name=financialBranch]").val() == ""){
	  			 Layer.showFailMsg("【融资产品】为必填字段！");
	  			 return false;
	  		 }
	  		 if($("select[name=financialProportion]").val() == null || $("select[name=financialProportion]").val() == ""){
	  			 Layer.showFailMsg("【融资比例】为必填字段！");
	  			 return false;
	  		 }
	  		 
	  		 if($("input[name=allottedTime]").val() == null || $("input[name=allottedTime]").val() == ""){
	  			 Layer.showFailMsg("期限不能为空！");
	  			 return false;
	  		 }else{
	  			 var allottedTime = $("input[name=allottedTime]").val();
	  			 if(!isPositiveInteger(allottedTime)) {
	  				Layer.showFailAlert("期限只能输入正整数！",0) 
	  				return false; 
	  			 }
	  			 if(allottedTime >next_deadline_limt  || allottedTime < up_deadline_limt ){
	  				 Layer.showFailMsg("期限范围只能输入【"+up_deadline_limt+"~"+next_deadline_limt+"】");
	  				 return false;
	  			 }
	  		 }
	  		var totalMoney = $('input[name=totalMoney]').val()*10000;
			if(totalMoney > creditlimit){
				 Layer.showFailAlert("融资金额不可大于授信额度", 0);
				 return  false;  
			}
	  	 }
    	
      	 var deliveryWay = $("input[name='deliveryWay']:checked").val();
      	 if(typeof(deliveryWay) == 'undefined' || deliveryWay == ''){
      		 Layer.showFailMsg("【配送方式】为必填字段");
      		 return false;
      	 }
      	if(isPoneAvailable($("input[name=receiveTel]").val()) == false){
      		 Layer.showFailMsg("【联系电话】格式不正确！");
     		 return false;
      	}
      	
      	
    	 if($("input[name=receiveIdCard]").val()){
    		var receiveIdCard = $("input[name=receiveIdCard]").val();
     	    // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X  
     	    var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;  
     	    if(reg.test(receiveIdCard) === false)  {  
     	    	Layer.showFailMsg("身份证输入不合法,身份证号码格式为15位或者18位！");  
     	        return  false;  
     	    }  
  	     }
  	   if(!checkflag){return false;}
       var datas = data.field;
         // 下意向订单
         $.ajax({
     		url: hostUrl+'/purchaseIntentioOrderHead/saveIntentioOrder',
             type: "post",
             data: datas,
             dataType: "json",
             success: function(data) {
            	 if(data.status == 0){
            		 Layer.showSucMsg("下意向订单成功");
            		 closeMyself();
            	 }else{
            		 Layer.showAlert("下意向订单失败");
            	 }
             },
     	 	error: function(data) { 
      		 	Layer.showAlert("下意向订单失败");
     	 	}
         });
         
       });
       function isPoneAvailable(poneInput) {
           var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
           if (!myreg.test(poneInput)) {
               return false;
           } else {
               return true;
           }
       }
     //是否为正整数
     function isPositiveInteger(s){
    	     var re = /^[0-9]+$/ ;
    	     return re.test(s);
      }  
     //关闭弹出框
       function closeMyself(){
       	var index = parent.layer.getFrameIndex(window.name);
       	parent.layer.close(index);
       }
       
       function toThousands(num) {
    	    return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
    	}
    });
});